<?php

namespace addons\third\library;

use hillpy\MiniProgramSDK\Common;
use hillpy\MiniProgramSDK\MiniProgram;
use think\Config;

/**
 * 微信小程序
 */
class WechatMini
{
    const GET_USERINFO_URL = "https://api.weixin.qq.com/sns/userinfo";
    const GET_ACCESS_TOKEN_URL = "https://api.weixin.qq.com/sns/oauth2/access_token";
    /**
     * 配置信息
     * @var array
     */
    private $config = [];
    /**
     * @var null
     */
    private static $miniProgram = null;

    public function __construct($options = [])
    {
        if ($config = Config::get('third.wechatmini')) {
            $this->config = array_merge($this->config, $config);
        }
        $this->config = array_merge($this->config, is_array($options) ? $options : []);

        if (self::$miniProgram == null) {
            self::$miniProgram = new MiniProgram($this->config['app_id'], $this->config['app_secret']);
        }
    }

    public function jscode2session($code)
    {
        return self::$miniProgram->jscode2Session($code);
    }

    public function decryptData($params)
    {
        $data = self::$miniProgram->decryptData($params);
        $data['data'] = array_merge($data['data'], self::$miniProgram->accessTokenData);
        return $data;
    }

    /**
     * 获取用户信息
     * @param array $params
     * @return array
     */
    public function getUserInfo($params = [])
    {
        $params = $params ? $params : request()->get();
        if (isset($params['code'])) {
            //获取access_token
            $data = isset($params['code']) ? $this->jscode2session($params['code']) : $params;
            if (isset($data['errcode'])) {
                $res['code'] = -101;
                $res['msg'] = Common::getErrorMsg($data['errcode']);
                return $res;
            }

            $openid = isset($data['openid']) ? $data['openid'] : '';
            $sessionKey = isset($data['session_key']) ? $data['session_key'] : '';
            $unionid = isset($data['unionid']) ? $data['unionid'] : '';

            $data = [
                'sessionKey' => $sessionKey,
                'openid' => $openid,
                'unionid' => $unionid,
            ];
            $res['code'] = 0;
            $res['data'] = $data;
            return $res;
        }
        return [];
    }
}
